package main

import (
	"encoding/json"
	"io"
)

// TODO add timeout
func DecodeMessage(r io.Reader) (*Message, error) {
	header := &MessageHeader{}
	err := header.Decode(r)
	if err != nil {
		return nil, err
	}
	buf := make([]byte, header.Length)
	_, err = r.Read(buf)
	if err != nil {
		return nil, err
	}
	message := &Message{}
	switch header.Type {
	case MT_SUBMIT_JOB:
		message.Type = MT_SUBMIT_JOB
		jobConf := NewJobConf()
		err := json.Unmarshal(buf, &jobConf)
		if err != nil {
			return nil, err
		}
		message.Body = jobConf
	case MT_KILL_JOB:
		message.Type = MT_KILL_JOB
		jobConf := NewJobConf()
		err := json.Unmarshal(buf, &jobConf)
		if err != nil {
			return nil, err
		}
		message.Body = jobConf
	case MT_EXIT:
		message.Type = MT_EXIT
	case MT_LOG_RESP:
		message.Type = MT_LOG_RESP
	default:
		message.Type = int(header.Type)
	}
	return message, nil
}

func EncodeMessage(message *Message, w io.Writer) error {
	data, err := json.Marshal(message.Body)
	if err != nil {
		return err
	}
	//log.Debugf("encode message: %s", string(data))
	header := &MessageHeader{
		Version: PROTOCOL_VERSION,
		Length:  uint32(len(data)),
		Type:    uint32(message.Type),
	}
	buf := header.Encode()
	if err != nil {
		return err
	}
	w.Write(buf)
	w.Write(data)
	return nil
}
